<?php
declare(strict_types=1);

namespace ServerApp\lib\server\udp;

use ServerApp\lib\memory\Chan;
use ServerApp\lib\process\SGlobal;
use ServerApp\lib\process\SProcess;
use ServerApp\lib\server\conf\ConfStation;
use ServerApp\lib\util\ServerHelper;
use stdClass;

/**
 *
 */
class Task
{
    private $server_arr = [];

    public function __construct()
    {
        $GLOBALS['port_que'] = [];
        $tmp = new stdClass();
        $tmp->func = function() use ($tmp){
            while ($data = Chan::getInstance()->pop()) {
                $arr = explode(Udp::SPLIT, $data);
                $this->handleCmd(array_shift($arr), $arr);
            }
            swoole_timer_after(1000, $tmp->func);
        };
        ($tmp->func)();
    }

    private function handleCmd($cmd, $arr){
        switch ($cmd){
            case ConfStation::SERVERS:
                $this->changeServers($arr);
                break;
            case ConfStation::SWITCH:
                $this->switch($arr);
                break;
            default:
                break;
        }

    }

    private function changeServers($arr){
        list($json_str) = $arr;
        if (!$json_str) {
            $this->server_arr = [];
        } else {
            $this->server_arr = json_decode($json_str, true);
        }
        tracker(D, $this->server_arr);
    }

    private function switch($arr){

        list($port, $to, $mid, $data) = $arr;
        if(!isset($GLOBALS['port_que'][$port])) {
            $process = new SProcess(function() use($port){
                SGlobal::getInstance()->process->useQueue(Udp::getFtokKey($port), 2);
                swoole_event_add(SGlobal::getInstance()->process->pipe, function(){
                    $data = SGlobal::getInstance()->process->read();
                    tracker(D, $data);
                    SGlobal::getInstance()->process->push($data);
                });
            }, false, 2);
            $GLOBALS['port_que'][$port] = $process;

            $content = $process->start();
            $s = explode('\\', __CLASS__);
            file_put_contents(ServerHelper::getInstance()->getPidPath() . end($s) . __LINE__ . "_$port.pid", $content);
        }
        /** @var SProcess $process */
        $process = $GLOBALS['port_que'][$port];
        $process->write(join("\v", [
            $to, $mid, $data
        ]));
    }
}